//
//  CollectViewController.m
//  SHShopping
//
//  Created by 坤鼎 on 2019/9/2.
//  Copyright © 2019 kunding. All rights reserved.
//

#import "CollectViewController.h"
#import "DiscoverTableViewCell.h"
#import "PublicRightImageCell.h"
#import "PublicThreeImageCell.h"
#import "MPMoviePlayerVC.h"

@interface CollectViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *tableViewDataArrModel;
@property (nonatomic, assign) NSInteger refreshCount;//上滑次数
@property (nonatomic, assign) NSInteger totalCount;//列表个数

@property (nonatomic, strong) ListNightSHTweetModel *shareDataModel;


@end

@implementation CollectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的收藏";
    [self.view addSubview:self.tableView];
    
    // 添加头部的下拉刷新
    MJRefreshNormalHeader *header = [[MJRefreshNormalHeader alloc] init];
    [header setRefreshingTarget:self refreshingAction:@selector(headerClick)];
    self.tableView.mj_header = header;
    [header beginRefreshing];
    
    // 添加底部的上拉加载
    MJRefreshBackNormalFooter *footer = [[MJRefreshBackNormalFooter alloc] init];
    [footer setRefreshingTarget:self refreshingAction:@selector(footerClick)];
    self.tableView.mj_footer = footer;
    
    self.tableView.rowHeight = UITableViewAutomaticDimension; // 自适应xib高度
    self.tableView.estimatedRowHeight = 200; //先估计一个高度
}
// 头部的下拉刷新触发事件
- (void)headerClick {
    [self loadNetData];
    // 结束刷新
    [self.tableView.mj_header endRefreshing];
}
// 底部的上拉加载触发事件
- (void)footerClick {
    
    self.refreshCount++;
    [self addData];
}

- (void)loadNetData {
    self.refreshCount = 1;
    if (self.tableViewDataArrModel.count != 0) {
        [self.tableViewDataArrModel removeAllObjects];
    }
    
    NSDictionary *par = @{@"userId":[UserManager sharedUserManager].userInfo.uid,
                          @"page":@(self.refreshCount),
                          @"pageSize":@"10"
                          };
    [PPNetworkHelper POST:URL_getListCollect parameters:par success:^(id responseObject) {
        self.tableViewDataArrModel = [ListNightSHTweetModel arrayOfModelsFromDictionaries:responseObject[@"retBody"][@"rows"] error:nil];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
    }];
}

- (void)addData {
    NSDictionary *par = @{@"userId":[UserManager sharedUserManager].userInfo.uid,
                          @"page":@(self.refreshCount),
                          @"pageSize":@"10"
                          };
    
    [SXLoadingView showProgressHUD:nil];
    [PPNetworkHelper POST:URL_getListCollect parameters:par success:^(id responseObject) {
        [SXLoadingView hideProgressHUD];
        NSArray *arr = responseObject[@"retBody"][@"rows"];
        self.totalCount = [responseObject[@"retBody"][@"total"] integerValue];
        if (IsNotNilArr(arr)) {
            NSArray *modleArr = [ListNightSHTweetModel arrayOfModelsFromDictionaries:arr error:nil];
            [self.tableViewDataArrModel addObjectsFromArray:modleArr];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
    }];
}

#pragma mark - 友盟分享
- (void)shareAction:(UIButton *)sender {
    self.shareDataModel = self.tableViewDataArrModel[sender.tag - 1000];
    
    [self shareAlertView];
}

- (void)shareAlertView {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    //    蒙板
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    view.tag = 9998;
    view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
    [window addSubview:view];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRemoveShareView:)];
    [view addGestureRecognizer:tap];
    
    
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(16, SCREEN_HEIGHT - 120 - 28, SCREEN_WIDTH - 32, 120)];
    whiteView.backgroundColor = [UIColor whiteColor];
    whiteView.tag = 9999;
    ViewBorderRadius(whiteView, 10, 0, [UIColor whiteColor]);
    [window addSubview:whiteView];
    
    //间距
    float weight = 65;
    int range = (whiteView.frame.size.width - weight * 4) / 5;
    NSArray *arr = @[@"微信",
                     @"朋友圈",
                     @"QQ",
                     @"取消收藏"];
    
    for (int i = 0; i < arr.count; i++) {
        UIButton *imageBtn = [[UIButton alloc] initWithFrame:CGRectMake(range + i * (weight + range), 20, weight, weight)];
        [imageBtn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"分享%d", i]] forState:UIControlStateNormal];
        if (i == 3) {
            [imageBtn setImage:ImageNamed(@"分享3_Y") forState:UIControlStateNormal];
        }
        [imageBtn addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        imageBtn.tag = i + 10000;
        [imageBtn setTitle:arr[i] forState:UIControlStateNormal];
        [whiteView addSubview:imageBtn];
        
        UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(range + i * (weight + range), GetViewYH(imageBtn), weight, 17)];
        lb.tag = i + 10010;
        lb.textColor = UIColorFromRGB(0x333333);
        lb.font = FONT(12);
        lb.text = arr[i];
        lb.textAlignment = 1;
        [whiteView addSubview:lb];
    }
    //    if (![QQApiInterface isQQInstalled]) {//没有安装QQ
    //        UIButton *btn = [whiteView viewWithTag:10002];
    //        btn.hidden = YES;
    //
    //        UILabel *lb = [whiteView viewWithTag:10012];
    //        lb.hidden = YES;
    //    }
    //    if (![WXApi isWXAppInstalled]) { //没有安装微信
    //        UIButton *btn0 = [whiteView viewWithTag:10000];
    //        UIButton *btn1 = [whiteView viewWithTag:10001];
    //        btn0.hidden = YES;
    //        btn1.hidden = YES;
    //
    //        UILabel *lb0 = [whiteView viewWithTag:10010];
    //        UILabel *lb1 = [whiteView viewWithTag:10011];
    //        lb0.hidden = YES;
    //        lb1.hidden = YES;
    //    }
}

- (void)shareBtnAction:(UIButton *)sender {
    [self removeShareView];
    NSInteger platformType = 0;
    switch (sender.tag) {
            case 10000: {
                platformType = 1;//微信聊天
            }
            break;
            case 10001: {
                platformType = 2;//微信朋友圈
            }
            break;
            case 10002: {
                platformType = 4;//QQ聊天
            }
            break;
            case 10003: {
                NSDictionary *par = @{@"userId":DSStringValue([UserManager sharedUserManager].userInfo.uid),
                                      @"tweetId":DSStringValue(self.shareDataModel.id)
                                      };
                
                [PPNetworkHelper POST:URL_delCollect parameters:par success:^(id responseObject) {
                    [SXLoadingView showAlertHUD:responseObject[@"retMsg"] duration:SXLoadingTime];
                    [self loadNetData];
                } failure:^(NSError *error) {
                    [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
                }];
                
                return;
            }
            break;
            
        default:
            break;
    }
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //创建网页内容对象
    NSString *thumbURL = self.shareDataModel.imgPath[0];
    
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.shareDataModel.fromName descr:self.shareDataModel.title thumImage:thumbURL];
    //设置网页地址
    shareObject.webpageUrl = self.shareDataModel.linkPath;
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************分享失败 %@*********",error);
        } else {
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"响应消息 %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"原始响应数据 %@",resp.originalResponse);
            } else {
                UMSocialLogInfo(@"响应数据 %@",data);
            }
        }
    }];
}

- (void)tapRemoveShareView:(UITapGestureRecognizer *)tap {
    [self removeShareView];
}

- (void)removeShareView {
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    UIView *view0 = [window viewWithTag:9998];
    UIView *view1 = [window viewWithTag:9999];
    
    [view0 removeFromSuperview];
    [view1 removeFromSuperview];
}

#pragma mark --UITableView代理

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    [tableView tableViewDisplayWitMsg:@"您还没有收藏哟~" ifNecessaryForRowCount:self.tableViewDataArrModel.count image:@"noCollect"];
    //刷新数据处理
    self.tableView.mj_footer.hidden = (self.tableViewDataArrModel.count == 0);
    if (self.tableViewDataArrModel.count == self.totalCount) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
    return self.tableViewDataArrModel.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    ListNightSHTweetModel *model = self.tableViewDataArrModel[indexPath.row];
    /**
     1一张图 2三张图 3视频
     */
    if (model.cssType == 3) {
        MPMoviePlayerVC *vc = [[MPMoviePlayerVC alloc] init];
        vc.videoTitle = model.title;
        vc.videoPath = model.videoPath;
        vc.fromName = model.fromName;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        WKWebViewController *webVC = [[WKWebViewController alloc] initWithURLString:DSStringValue(model.linkPath)];
        webVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:webVC animated:YES];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ListNightSHTweetModel *model = self.tableViewDataArrModel[indexPath.row];
    switch (model.cssType) {
            case 1: {//一张小图
                static NSString *CellIdentifier = CellID_PublicRightImageCell;
                PublicRightImageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                if (cell == nil) {
                    cell = [[PublicRightImageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                }
                cell.shareBtn.tag = indexPath.row + 1000;
                [cell.shareBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
                [cell updatePublicRightImageCellWithModel:model];
                return cell;
            }
            break;
            case 2: {//三张小图
                static NSString *CellIdentifier = CellID_PublicThreeImageCell;
                PublicThreeImageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                if (cell == nil) {
                    cell = [[PublicThreeImageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                }
                cell.shareBtn.tag = indexPath.row + 1000;
                [cell.shareBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
                [cell updatePublicThreeImageCellWithModel:model];
                return cell;
            }
            break;
            case 3: {//视频
                static NSString *CellIdentifier = CellID_DiscoverTableViewCell;
                DiscoverTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                if (cell == nil) {
                    cell = [[DiscoverTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                }
                cell.imageVideo.hidden = NO;
                cell.shareBtn.tag = indexPath.row + 1000;
                [cell.shareBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
                [cell updateDiscoverTableViewCellWithModel:model];
                return cell;
            }
            break;
        default: {//一张大图
            static NSString *CellIdentifier = CellID_DiscoverTableViewCell;
            DiscoverTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[DiscoverTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            cell.imageVideo.hidden = YES;
            cell.shareBtn.tag = indexPath.row + 1000;
            [cell.shareBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
            [cell updateDiscoverTableViewCellWithModel:model];
            return cell;
        }
            break;
    }
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - kNavBarAndStatusBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"DiscoverTableViewCell" bundle:nil] forCellReuseIdentifier:CellID_DiscoverTableViewCell];
        [_tableView registerNib:[UINib nibWithNibName:@"PublicRightImageCell" bundle:nil] forCellReuseIdentifier:CellID_PublicRightImageCell];
        [_tableView registerNib:[UINib nibWithNibName:@"PublicThreeImageCell" bundle:nil] forCellReuseIdentifier:CellID_PublicThreeImageCell];
    }
    return _tableView;
}

- (NSMutableArray *)tableViewDataArrModel {
    if (!_tableViewDataArrModel) {
        _tableViewDataArrModel = [[NSMutableArray alloc] init];
    }
    return _tableViewDataArrModel;
}

@end
